package com.iplay.实战java高并发程序设计.chapter2;

/**
 * Thread.sleep()方法由于中断而抛出异常，此时它会清除中断标记，如果不处理，那么在下一次循环开始时，就无法捕获这个中断，故在异常处理中，
 * 再次设置中断标记位
 * @author dangwu
 * @since 2021/10/13 5:51 下午
 */
public class InterruptTest {
    public static void main(String[] args) throws InterruptedException{
        final int[] i = {0};
        Thread t = new Thread(){
            @Override
            public void run() {
                while (true){
                    if (Thread.currentThread().isInterrupted()){
                        System.out.println("Interrupted");
                        break;
                    }
                    System.out.println(i[0]++);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        System.out.println("Interrupted when sleep");
                        //这次，设置中断状态
                        Thread.currentThread().interrupt();
                    }
                    Thread.yield();
                }
            }
        };
        t.start();
        Thread.sleep(200);
        t.interrupt();
    }
}
